#coding:utf-8
import os
import json
import time
from flask import Flask, request, jsonify, abort
from group_id import NewsFingerPrint


app = Flask(__name__)
group_id_client = NewsFingerPrint(logger=app.logger) 



def input_check(data):
    if not data:    return False
    for field in ['title', 'dataid', 'ctime']:
        if field not in data:
            return False
    return True

@app.route('/group_id/', methods = ['GET','POST'])
def news_fp():
    if request.method == 'GET':
        data = request.args.get('data',{})
    else:
        input_data=json.loads(request.get_data())
        data = input_data.get('data', {})

    if not input_check(data):
        app.logger.info("input data empty! data:{}".format(data))
        return jsonify(
            code = '01', msg = 'input data empty! data:{}'.format(data), ret = {})
    try:
        _st  = time.time()
        ret  = group_id_client.group_id(data)
        _end = time.time()
    except Exception as e:
        app.logger.error("data:{}  msg:{}".format(data, e))
        return jsonify(code = '02', msg = 'server error! {}'.format(e), ret = {})

    return jsonify(
        code         = '00',
        time_consume = '{} ms'.format((_end-_st)*1000),
        ret          = ret,
        msg          = 'ok'
        )
   

if __name__ == '__main__':
    #app.run('0.0.0.0',3412)
    app.run()     
